package cloud.seata.config;


import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
//自定义数据库连接池的自动配置类，在启动类启动时把原来的数据库连接池类排除不加载
public class DataSourceProxyConfig {

    @Value("${mybatis.mapperLocations}")
    //将配置文件的信息加载进来
    private String mapperLocations;

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    //在将对象放入ioc容器前，读取配置文件的部分信息并设置给对象
    public DataSource druidDataSource(){
        return new DruidDataSource();
    }

    @Bean
    //生成数据库连接池代理对象
    public DataSourceProxy dataSourceProxy(DataSource dataSource) {
        return new DataSourceProxy(dataSource);
    }

    @Bean
    //生成Mybatis会话工厂，并设置其属性，后面获取会话对象并放入IOC容器
    public SqlSessionFactory sqlSessionFactoryBean(DataSourceProxy dataSourceProxy) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSourceProxy);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
        sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
        return sqlSessionFactoryBean.getObject();
    }

}
